import { createContext, useContext, ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { authApi } from "../api/auth.ts";

interface AuthContextType {
  isAuthenticated: boolean;
  setIsAuthenticated: (value: boolean) => void;
  isLoading: boolean;
  refetchAuth: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
  const { 
    data, 
    isLoading, 
    refetch 
  } = useQuery({
    queryKey: ['auth', 'verify'],
    queryFn: async () => {
      const token = localStorage.getItem("token");
      if (!token) {
        return { valid: false };
      }
      try {
        const user = await authApi.verify();
        return { valid: true, user };
      } catch (error) {
        console.error('Token验证失败:', error);
        localStorage.removeItem("token");
        return { valid: false };
      }
    },
    retry: false,
    refetchOnWindowFocus: true,
    refetchInterval: 5 * 60 * 1000,
    staleTime: 4 * 60 * 1000,
  });

  const setIsAuthenticated = (value: boolean) => {
    if (!value) {
      localStorage.removeItem("token");
    }
    refetch();
  };

  const refetchAuth = async () => {
    await refetch();
  };

  return (
    <AuthContext.Provider 
      value={{ 
        isAuthenticated: data?.valid ?? false, 
        setIsAuthenticated,
        isLoading,
        refetchAuth
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
} 